package system

import (
	"context"
	"encoding/json"
	"fmt"
	"gf-assistant/internal/common/factory"
	"gf-assistant/internal/system/parameter"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"reflect"
)

type IndexDao struct{}

func init() {
	indexDao := IndexDao{}
	factory.Put(reflect.TypeOf(indexDao).String(), &indexDao)
}

// DB retrieves and returns the underlying raw database management object of current DAO.
func (dao *IndexDao) DB() gdb.DB {
	return g.DB()
}
func (dao *IndexDao) GetMenu(ctx context.Context, req *parameter.GetMenuReq) (menus []*parameter.MenuRes) {

	sql := `
		  SELECT distinct m.MENU_ID as Id,m.PARENT_ID as ParentId,m.MENU_NAME as Title,m.ICON as Icon,
		                  m.HREF as Href,m.TARGET as Target,m.SORT_NUM
		  FROM SYS_MENU m
		  JOIN SYS_ROLE_MENU SRM on m.MENU_ID=SRM.MENU_ID AND SRM.ENABLE_STATUS=1
		  JOIN SYS_ROLE R on SRM.ROLE_ID=R.ROLE_ID AND R.ENABLE_STATUS=1
		  JOIN SYS_USER_ROLE UR on R.ROLE_ID=UR.ROLE_ID AND UR.ENABLE_STATUS=1
		  JOIN SYS_USER U on UR.USER_ID=U.USER_ID AND U.ENABLE_STATUS=1
		  WHERE U.USER_ID=? AND m.ENABLE_STATUS=1 AND m.LEVEL<3
		  ORDER BY m.PARENT_ID,m.SORT_NUM DESC
		  `
	resultList, err := g.DB().GetAll(ctx, sql, req.GetUserId())
	if err != nil {
		fmt.Printf("query faied, error:[%v]", err.Error())
		return
	}
	//遍历结构体切片
	for _, v := range resultList {
		menu := parameter.MenuRes{}
		err = json.Unmarshal([]byte(v.Json()), &menu)
		if err != nil {
			fmt.Println("JSON unmarshal error:", err)
		}
		menus = append(menus, &menu)
	}
	return menus
}
